package top.javawa.token.web;

import java.util.List;
import java.util.Optional;
import javax.annotation.PostConstruct;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.javawa.token.domain.primary.AccessToken;
import top.javawa.token.domain.primary.AccessTokenRepository;

/**
 * @author aaron
 */
@Log
@RestController
@RequestMapping("/token")
public class TokenController {

  List<AccessToken> localTokens = null;

  @Autowired
  private AccessTokenRepository repository;

  @PostConstruct
  public void init() {
    // TODO 仅用于测试
    if (!repository.findByAppId("1000001").isPresent()) {
      AccessToken localToken = new AccessToken();
      localToken.setAppId("1000001");
      localToken.setExpiresIn(System.currentTimeMillis() + 2 * 60 * 60 * 1000);
      localToken.setToken("i'am token");
      repository.save(localToken);
    }
  }

  /**
   * 获取token，如果存在本地缓存且未过期则直接返回本地Token
   *
   * @return JsonObject token
   */
  @GetMapping("/all")
  public List<AccessToken> getAllToken() {
    if (localTokens == null) {
      Optional<List<AccessToken>> op = repository.findByAppId("1000001");
      if (op.isPresent()) {
        this.localTokens = op.get();
      }
    }
    return this.localTokens;
  }
}
